// internal/controller/url_controller.go
package controller

import (
	"URLshortener/internal/model"
	"URLshortener/internal/service"
	"errors"
	"github.com/gin-gonic/gin"
	"net/http"
)

type UrlController struct {
	service service.UrlService
}

func NewUrlController(s service.UrlService) *UrlController {
	return &UrlController{service: s}
}

// 处理表单提交
func (c *UrlController) HandleFormSubmit(ctx *gin.Context) {
	// 获取表单数据
	postUrl := model.RequestUrl{}
	postErr := ctx.ShouldBindBodyWithJSON(&postUrl)
	if postErr != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"message": "参数错误",
		})
		return
	}

	// 调用服务层
	shortCode, err := c.service.CreateShortUrl(ctx.Request.Context(), postUrl.OriginalUrl, postUrl.ExpireTime)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"shortcode": shortCode,
			"message":   getErrorMessage(err),
		})
		return
	}

	// 构建完整短链接
	fullShortUrl := ctx.Request.Host + "/" + shortCode

	ctx.JSON(http.StatusOK, gin.H{
		"shortUrl":   fullShortUrl,
		"resMessage": "短链接生成成功！",
	})
}

func (c *UrlController) HandleRedirect(ctx *gin.Context) {
	shortCode := ctx.Param("shortCode")
	originalUrl, err := c.service.GetOriginalUrl(ctx.Request.Context(), shortCode)
	if err != nil {
		ctx.JSON(http.StatusOK, gin.H{
			"message": getErrorMessage(err),
		})
		return
	}
	// 重定向
	ctx.Redirect(http.StatusMovedPermanently, originalUrl)
}

// 错误信息映射
func getErrorMessage(err error) string {
	switch {
	case errors.Is(err, service.ErrUrlExists):
		return "该URL已存在短链接"
	case errors.Is(err, service.ErrShortCodeConflict):
		return "短码已被占用"
	case errors.Is(err, service.ErrUrlExpired):
		return "链接已过期"
	default:
		return "服务器内部错误，请稍后再试"
	}
}
